package com.cn.lp.export.client.base.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * Description: 请描述你的文件
 *
 * @author wuqirong
 * @date 2020-10-20
 * <p>
 * All rights Reserved, Designed www.xiao100.com
 */

@Component
public class SpringUtils {

    @Autowired
    private ApplicationContext context;

    private static SpringUtils instance = null;

    {
        instance = this;
    }


    /**
     * 通过字节码获取
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> Optional<T> getBean(Class<T> beanClass) {
        if(instance == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(instance.context.getBean(beanClass));
    }

    /**
     * 通过BeanName获取
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> Optional<T> getBean(String beanName) {
        if(instance == null) {
            return Optional.empty();
        }
        return Optional.ofNullable((T) instance.context.getBean(beanName));
    }

    /**
     * 通过beanName和字节码获取
     * @param name
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> Optional<T> getBean(String name, Class<T> beanClass) {
        if(instance == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(instance.context.getBean(name, beanClass));
    }

}
